package com.jielin.handling.web.aop;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 类名称：LogAop   
 * 创建人：zhanglongdeng@163.com
 * 创建时间：2018年10月25日 下午12:05:10    
 * 类描述：web请求全局日志
 */
@Aspect
@Component
@Slf4j
public class LogAop {
	
	@Pointcut("execution(public * com.jielin.handling.controller.*.*.*(..))")
	public void logPointcut() {
		
	}
	
	@Before("logPointcut()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		log.info("AOP--->HTTP_URL : " + request.getRequestURL().toString());
		log.info("AOP--->HTTP_METHOD : " + request.getMethod());
		log.info("AOP--->HTTP_IP : " + request.getRemoteAddr());
		Enumeration<String> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String name = (String) enu.nextElement();
			log.info("AOP--->name:{},value:{}", name, request.getParameter(name));
		}
	}

	@AfterReturning(returning = "ret", pointcut = "logPointcut()")
	public void doAfterReturning(Object ret) throws Throwable {
		// 处理完请求，返回内容
		log.info("AOP--->HTTP_RESPONSE : " + JSONObject.toJSONString(ret));
	}

}